/*
 * @Author: sjf 1758142861@qq.com
 * @Date: 2023-03-21 15:32:43
 * @LastEditors: sjf 1758142861@qq.com
 * @LastEditTime: 2023-03-21 15:36:36
 * @FilePath: /D_C_lib/lw_process/day4/Thread.hpp
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
/*
 * @Author: sjf 1758142861@qq.com
 * @Date: 2023-03-21 14:54:41
 * @LastEditors: sjf 1758142861@qq.com
 * @LastEditTime: 2023-03-21 14:54:41
 * @FilePath: /D_C_lib/lw_process/day4/Thread.hpp
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#pragma once

#include<iostream>
#include<cstdio>
#include<cassert>
#include<string>
#include<functional>
#include<string.h>
#include<unistd.h>
#include<pthread.h>

class Thread;

class Context
{
public:
    Thread* _this;
    void* _args;
public:
    Context()
    :_this(nullptr)
    ,_args(nullptr)
    {}

    ~Context()
    {}
};

class Thread
{
public:
    typedef std::function<void*(void*)> func_t;
    const int NUM = 1024;
public:
    Thread(func_t func,void * args,int number)
    :__func(func)
    ,__args(args)
    {
        //char namebuffer[1024];
        char name_buffer[NUM];
        snprintf(name_buffer,sizeof(name_buffer),"thread-%d",number);
        __name = name_buffer;
        Context* ctx = new Context();
        ctx->_this = this;
        ctx->_args = __args;
        int n = pthread_create(&__tid,nullptr,start_routine,ctx);
        assert(n == 0);
        (void)n;
    }

    static void *start_routine(void* args)
    {
        Context *ctx = static_cast<Context*>(args);
        void* ret = ctx->_this->run(ctx->_args);
        delete ctx;
        return ret;
    }

    void join()
    {
        int n = pthread_join(__tid,nullptr);
        assert(n == 0);
        (void)n;
    }

    void *run(void* args)
    {
        return __func(args);
    }

    ~Thread()
    {}
private:
    std::string __name; // 线程名称
    func_t __func; //待执行函数
    void* __args; //线程执行方法
    pthread_t __tid; //线程的lwp
};